<script lang="ts" setup>
import {nextTick, ref,watch, onMounted} from 'vue'
import { ElInput } from 'element-plus'
import type { InputInstance } from 'element-plus'


const parentDynamicTags =defineModel()

const inputValue = ref('')


const dynamicTags = ref([])

onMounted(()=>{
  dynamicTags.value=parentDynamicTags.value
})

watch(dynamicTags.value,(newValue,oldValue)=>{
  parentDynamicTags.value=newValue
})

const inputVisible = ref(false)
const InputRef = ref<InputInstance>()

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
    console.log(parentDynamicTags)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<template>
  <div class="flex gap-2">
    <el-tag style="margin-right: 10px"
        v-for="tag in dynamicTags"
        :key="tag"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="w-20"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="small" @click="showInput">
      添加标签
    </el-button>
  </div>
</template>

<style scoped lang="less">

</style>